using UniversalAdminSystem.Application.Common.Results;
using UniversalAdminSystem.Application.UserManagement.Dtos;
using UniversalAdminSystem.Application.UserManagement.Interface;
using UniversalAdminSystem.Domian.UserManagement.Aggregates;
using UniversalAdminSystem.Domian.UserManagement.Entities;
using UniversalAdminSystem.Domian.UserManagement.IRepository;
using UniversalAdminSystem.Domian.UserManagement.ValueObj;
using UniversalAdminSystem.Application.PermissionManagement.Interfaces;
using UniversalAdminSystem.Domian.Core.ValueObjects;
using UniversalAdminSystem.Domian.PermissionManagement.IRepository;
using UniversalAdminSystem.Application.Common.Interfaces;

namespace UniversalAdminSystem.Application.UserManagement.Service;

public class UserManagementAppService : IUserManagementAppService
{
    private readonly IUserRepository _userRepo;
    private readonly IUserInfoRepository _userInfoRepo;
    private readonly IRoleRepository _roleRepo;
    private readonly IPasswordHelper _passwordHelper;
    private readonly IUnitOfWork _unitOfWork;
    private readonly IPermissionCheckService _permissionCheckService;
    // private readonly UserPermissionIntegrationService _userPermissionIntegration;
    // private readonly ICurrentUserContext _currentUserContext;

    public UserManagementAppService(
        IUserRepository user,
        IUserInfoRepository userInfo,
        IRoleRepository role,
        IPasswordHelper password,
        IUnitOfWork Wokr,
        IPermissionCheckService permissionCheckService)
    {
        _userRepo = user;
        _userInfoRepo = userInfo;
        _roleRepo = role;
        _passwordHelper = password;
        _unitOfWork = Wokr;
        _permissionCheckService = permissionCheckService;
        // _userPermissionIntegration = userPermissionIntegration;
        // _currentUserContext = currentUserContext;
    }

    public async Task<Result<IEnumerable<UserDto>>> GetUsersAsync()
    {
        try
        {
            // 权限验证：检查当前用户是否有权限查看用户列表
            // var currentUserId = _currentUserContext.GetCurrentUserId();
            // if (!currentUserId.HasValue)
            // {
            //     return Result<IEnumerable<UserDto>>.Failure("用户未登录");
            // }

            // if (!await _permissionCheckService.CheckUserPermissionAsync(currentUserId.Value, "user:read"))
            // {
            //     return Result<IEnumerable<UserDto>>.Failure("没有权限查看用户列表");
            // }

            var users = await _userRepo.GetAllAsync();
            var Roles = await _roleRepo.GetByNameAsync("普通用户") ?? throw new Exception("用户角色查询失败");
            var RoleId = users.Select(x => x.RoleId != null ? x.RoleId.Value : Roles.RoleId.Value);
            var Role = await _roleRepo.GetByIdsAsync(RoleId);
            var list = users.Select(x => new UserDto(x.UserId.Value, x.Account, x.Email, x.Status,
            Role.FirstOrDefault(r => r.RoleId.Value == x.RoleId.Value).Name));
            return Result<IEnumerable<UserDto>>.Success(list);
        }
        catch (Exception ex)
        {
            return Result<IEnumerable<UserDto>>.Failure($"获取用户列表失败: {ex.Message}");
        }
    }

    public async Task<Result<UserDto>> CreateUserAsync(UserCreateDto createDto)
    {
        try
        {
            // 权限验证：检查当前用户是否有权限创建用户
            // var currentUserId = _currentUserContext.GetCurrentUserId();
            // if (!currentUserId.HasValue)
            // {
            //     return Result<UserDto>.Failure("用户未登录");
            // }

            // if (!await _permissionCheckService.CheckUserPermissionAsync(currentUserId.Value, "user:create"))
            // {
            //     return Result<UserDto>.Failure("没有权限创建用户");
            // }

            await _unitOfWork.BeginTransactionAsync();

            // 1. 创建用户信息模板并保存
            var userInfo = UserInfo.CreateUserInfo();
            var info = await _userInfoRepo.AddAsync(userInfo);

            // 2. 密码加密与盐生成
            var (hashedPassword, salt) = _passwordHelper.HashPasswordWithSeparateSalt(createDto.Password);
            var Role = await _roleRepo.GetByNameAsync("普通用户") ?? throw new Exception("用户创建失败");
            // 3. 创建用户账户并保存
            var user = User.CreateUser(info.UserInfoId, createDto.Account, hashedPassword, createDto.Email, salt, UserStatus.Normal, Role.RoleId.Value);
            try
            {
                var savedUser = await _userRepo.AddAsync(user);
                await _unitOfWork.CommitAsync();
                // 4. 返回基础信息DTO
                return Result<UserDto>.Success(new UserDto(savedUser.UserId.Value, savedUser.Account, savedUser.Email, savedUser.Status));
            }
            catch (System.Exception)
            {
                throw new Exception("用户已存在");
            }
        }
        catch (System.Exception e)
        {
            await _unitOfWork.RollbackAsync();
            return Result<UserDto>.Failure($"创建用户失败: {e.Message}");
        }
    }

    public async Task<Result> DeleteUserAsync(Guid id)
    {
        try
        {
            var user = await _userRepo.GetByGuidAsync(id);
            if (user == null) return Result.Failure("用户不存在");
            if (user.Status == UserStatus.Logout) return Result.Failure("用户已被注销");
            if (user.Status == UserStatus.Freeze) return Result.Failure("用户已被冻结");

            // 权限验证：检查当前用户是否有权限删除目标用户
            // var currentUserId = _currentUserContext.GetCurrentUserId();
            // if (!currentUserId.HasValue)
            // {
            //     return Result.Failure("用户未登录");
            // }

            // if (!await _userPermissionIntegration.CanDeleteUserAsync(currentUserId.Value, id))
            // {
            //     return Result.Failure("没有权限删除该用户");
            // }

            await _unitOfWork.BeginTransactionAsync();
            await _userRepo.DeleteUserSoftAsync(id);
            await _unitOfWork.CommitAsync();
            return Result.Success("用户删除成功");
        }
        catch (Exception e)
        {
            await _unitOfWork.RollbackAsync();
            return Result.Failure($"删除用户失败: {e.Message}");
        }
    }

    public async Task<Result> AssignRoleAsync(Guid userId, List<Guid> roleIds)
    {
        try
        {
            var user = await _userRepo.GetByGuidAsync(userId);
            if (user == null) return Result.Failure("用户不存在");

            // 权限验证：检查当前用户是否有权限为目标用户分配角色
            // var currentUserId = _currentUserContext.GetCurrentUserId();
            // if (!currentUserId.HasValue)
            // {
            //     return Result.Failure("用户未登录");
            // }

            // if (!await _userPermissionIntegration.CanAssignRolesAsync(currentUserId.Value, userId, roleIds))
            // {
            //     return Result.Failure("没有权限为该用户分配角色");
            // }

            foreach (var rid in roleIds)
            {
                user.AssignRole((RoleId)rid);
            }
            await _unitOfWork.SaveChangesAsync();
            return Result.Success("角色分配成功");
        }
        catch (Exception ex)
        {
            return Result.Failure($"分配角色失败: {ex.Message}");
        }
    }

    public async Task<Result> RemoveRoleAsync(Guid userId, Guid roleId)
    {
        try
        {
            var user = await _userRepo.GetByGuidAsync(userId);
            if (user == null) return Result.Failure("用户不存在");

            // 权限验证：检查当前用户是否有权限移除用户角色
            // var currentUserId = _currentUserContext.GetCurrentUserId();
            // if (!currentUserId.HasValue)
            // {
            //     return Result.Failure("用户未登录");
            // }

            // if (!await _permissionCheckService.CheckUserPermissionAsync(currentUserId.Value, "user:manage"))
            // {
            //     return Result.Failure("没有权限管理用户角色");
            // }

            user.RemoveRole((RoleId)roleId);
            await _unitOfWork.SaveChangesAsync();
            return Result.Success("角色移除成功");
        }
        catch (Exception ex)
        {
            return Result.Failure($"移除角色失败: {ex.Message}");
        }
    }

    public async Task<Result<UserDetailDto>> GetUserByIdAsync(Guid userId)
    {
        try
        {
            // 权限验证：检查当前用户是否有权限查看用户详情
            // var currentUserId = _currentUserContext.GetCurrentUserId();
            // if (!currentUserId.HasValue)
            // {
            //     return Result<UserDto>.Failure("用户未登录");
            // }

            // if (!await _permissionCheckService.CheckUserPermissionAsync(currentUserId.Value, "user:read"))
            // {
            //     return Result<UserDto>.Failure("没有权限查看用户详情");
            // }

            var user = await _userRepo.GetByGuidAsync(userId);
            if (user == null) return Result<UserDetailDto>.Failure("用户不存在");
            UserInfo? userInfo = null;
            if (user.UserInfoId != null)
            {
                userInfo = await _userInfoRepo.GetByGuidAsync(user.UserInfoId);
            }
            return Result<UserDetailDto>.Success(new UserDetailDto(user.UserId.Value, user.Account, user.Email, user.Status, userInfo));
        }
        catch (Exception ex)
        {
            return Result<UserDetailDto>.Failure($"获取用户详情失败: {ex.Message}");
        }
    }

    public async Task<Result> UpdateUserAsync(Guid userId, UserUpdateDto updateDto)
    {
        try
        {
            var user = await _userRepo.GetByGuidAsync(userId);
            if (user == null)
            {
                return Result.Failure("用户不存在");
            }
            if (updateDto == null)
            {
                return Result.Failure("为传入数据");
            }
            Console.WriteLine("检查更新用户数据传输对象-------------- ");
            Console.WriteLine($"检查账号: {updateDto.Account}");
            Console.WriteLine($"检查账号: {updateDto.Email}");
            Console.WriteLine($"检查账号: {updateDto.StatusCode}");
            Console.WriteLine($"检查账号: {updateDto.Password}");
            Console.WriteLine("检查结束-----------");


            // 权限验证：检查当前用户是否有权限更新用户信息
            // var currentUserId = _currentUserContext.GetCurrentUserId();
            // if (!currentUserId.HasValue)
            // {
            //     return Result.Failure("用户未登录");
            // }

            // if (!await _permissionCheckService.CheckUserPermissionAsync(currentUserId.Value, "user:update"))
            // {
            //     return Result.Failure("没有权限更新用户信息");
            // }

            await _unitOfWork.BeginTransactionAsync();

            // 更新用户信息
            if (!string.IsNullOrEmpty(updateDto.Email))
            {
                user.UpdateUserEmail(updateDto.Email);
            }

            // 如果提供了新密码，则更新密码
            if (!string.IsNullOrEmpty(updateDto.Password))
            {
                var (hashedPassword, salt) = _passwordHelper.HashPasswordWithSeparateSalt(updateDto.Password);
                user.UpdateUserPassword(hashedPassword, salt);
            }
            var userStatus = (UserStatus)updateDto.StatusCode;
            user.UpdateUserStatus((UserStatus)updateDto.StatusCode);

            await _userRepo.Update(user);
            await _unitOfWork.CommitAsync();

            return Result.Success("用户信息更新成功");
        }
        catch (Exception e)
        {
            await _unitOfWork.RollbackAsync();
            return Result.Failure($"更新用户信息失败: {e.Message}");
        }
    }

    public async Task<Result<IEnumerable<string>>> GetUserPermissionsAsync(Guid userId)
    {
        try
        {
            // 权限验证：检查当前用户是否有权限查看用户权限
            // var currentUserId = _currentUserContext.GetCurrentUserId();
            // if (!currentUserId.HasValue)
            // {
            //     return Result<IEnumerable<string>>.Failure("用户未登录");
            // }

            // if (!await _permissionCheckService.CheckUserPermissionAsync(currentUserId.Value, "user:read"))
            // {
            //     return Result<IEnumerable<string>>.Failure("没有权限查看用户权限");
            // }

            var user = await _userRepo.GetByGuidAsync(userId);
            if (user == null) return Result<IEnumerable<string>>.Failure("用户不存在");
            if (user.RoleId == null) return Result<IEnumerable<string>>.Failure("用户角色不存在");
            var role = await _roleRepo.GetByGuidAsync(user.RoleId.Value);
            if (role == null) return Result<IEnumerable<string>>.Failure("用户角色不存在");
            var permissions = role.Permissions.Select(x => x.Code.Value);
            return Result<IEnumerable<string>>.Success(permissions);
        }
        catch (Exception ex)
        {
            return Result<IEnumerable<string>>.Failure($"获取用户权限失败: {ex.Message}");
        }
    }

    // public async Task<Result<IEnumerable<string>>> GetUserRolesAsync(Guid userId)
    // {
    //     try
    //     {
    //         // 权限验证：检查当前用户是否有权限查看用户角色
    //         var currentUserId = _currentUserContext.GetCurrentUserId();
    //         if (!currentUserId.HasValue)
    //         {
    //             return Result<IEnumerable<string>>.Failure("用户未登录");
    //         }

    //         if (!await _permissionCheckService.CheckUserPermissionAsync(currentUserId.Value, "user:read"))
    //         {
    //             return Result<IEnumerable<string>>.Failure("没有权限查看用户角色");
    //         }

    //         var roles = await _permissionCheckService.Get(userId);
    //         return Result<IEnumerable<string>>.Success(roles);
    //     }
    //     catch (Exception ex)
    //     {
    //         return Result<IEnumerable<string>>.Failure($"获取用户角色失败: {ex.Message}");
    //     }
    // }

    public async Task<Result<bool>> CheckUserPermissionAsync(Guid userId, string permissionCode)
    {
        try
        {
            // 权限验证：检查当前用户是否有权限检查其他用户权限
            // var currentUserId = _currentUserContext.GetCurrentUserId();
            // if (!currentUserId.HasValue)
            // {
            //     return Result<bool>.Failure("用户未登录");
            // }

            // if (!await _permissionCheckService.CheckUserPermissionAsync(currentUserId.Value, "user:read"))
            // {
            //     return Result<bool>.Failure("没有权限检查用户权限");
            // }

            var hasPermission = await _permissionCheckService.CheckUserPermissionAsync(userId, permissionCode);
            return Result<bool>.Success(hasPermission);
        }
        catch (Exception ex)
        {
            return Result<bool>.Failure($"检查用户权限失败: {ex.Message}");
        }
    }
}